package com.huatai.verity.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.api.R;
import com.huatai.common.util.StringUtil;
import com.huatai.verity.entity.ScreenUser;
import com.huatai.verity.mapper.ScreenUserMapper;
import com.huatai.verity.model.ScreenQueryModel;
import com.huatai.verity.service.ScreenUserService;
import com.huatai.verity.utils.Base64Utils;
import com.huatai.verity.utils.UUIDXUtil;
import com.huatai.verity.vo.LoginScreenUserVO;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static com.huatai.verity.constant.OtherConstant.*;
import static com.huatai.verity.constant.ScreenConstant.*;

/**
 * 大屏管理
 * @author chenwj
 */
@Service
public class ScreenUserServiceImpl extends ServiceImpl< ScreenUserMapper, ScreenUser > implements ScreenUserService {

	@Override
	public boolean saveScreenUser(ScreenUser screenUser) {
		if (StrUtil.isBlank(screenUser.getScPermissionId())){
			//设置状态正常
			screenUser.setForbidden(NOT_FORBIDDEN);
			screenUser.setScPermissionId(UUIDXUtil.getUUID(15));
		}
		return this.saveOrUpdate(screenUser);
	}

	@Override
	public R<String> login(String scName, String scPermissionId, String clientTime) {
		LoginScreenUserVO loginScreenUserVO = new LoginScreenUserVO();
		ScreenUser screenUser = baseMapper.selectOne(Wrappers.< ScreenUser >lambdaQuery()
			.eq(ScreenUser::getScName, scName)
			.eq(ScreenUser::getScPermissionId, scPermissionId));
		loginScreenUserVO.setScreenUser(screenUser);
		if (IS_PERMANENT.equals(screenUser.getPermanent())){
			loginScreenUserVO.setUseDays(99999L);
			//修改客户端时间,添加一个非法字段
			loginScreenUserVO.setIsIllegality(false);
			String screenUserVO = JSON.toJSONString(loginScreenUserVO);
			String encodeUser = Base64Utils.base64Encode(screenUserVO);
			return R.data(encodeUser,"永久用户");
		}
		//计算可用天数
		long useDay = this.popularUseDay(screenUser);
		loginScreenUserVO.setUseDays(useDay);
		//客户端时间时间转换,并比较二者相差的时间 超时  正负MAX_XC  分钟时   即为非法
		LocalDateTime clientDateTime = LocalDateTime.parse(clientTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		LocalDateTime now = LocalDateTime.now();
		Duration between = Duration.between(clientDateTime, now);
		long xc = between.toMinutes();
		//判断客户端时间是否正常   正常则记录,不正常则警告
		screenUser.setClientTime(clientDateTime);
		screenUser.setLoginTime(now);
		if (xc > MAX_XC || xc < -MAX_XC){
			//修改客户端时间,添加一个非法字段
			loginScreenUserVO.setIsIllegality(true);
			//禁用字段+1  当警告一次后,第二次则为禁用状态
			screenUser.setForbidden(screenUser.getForbidden()+1);
			this.saveScreenUser(screenUser);
			String screenUserVO = JSON.toJSONString(loginScreenUserVO);
			String encodeUser = Base64Utils.base64Encode(screenUserVO);
			return R.data(encodeUser,"有非法操作");
		}
		//更新客户端时间和,最近一次登录时间
		this.saveScreenUser(screenUser);
		String screenUserVO = JSON.toJSONString(loginScreenUserVO);
		String encodeUser = Base64Utils.base64Encode(screenUserVO);
		return R.data(encodeUser,"剩余可用时间为:"+useDay+"天");
	}

	@Override
	public R getListPage(ScreenQueryModel screenQueryModel) {
		Integer pageIndex = screenQueryModel.getPageIndex().equals(0)?1:screenQueryModel.getPageIndex();
		Integer pageSize = screenQueryModel.getPageSize().equals(0)?10:screenQueryModel.getPageSize();
		Page<ScreenUser> page = Page.of(pageIndex, pageSize);
		LambdaQueryWrapper< ScreenUser > queryWrapper = new LambdaQueryWrapper<>();
		//根据名字模糊查询
		if (StringUtil.isNotBlank(screenQueryModel.getCompanyName())) {
			queryWrapper.like(ScreenUser::getCompany, screenQueryModel.getCompanyName());
		}
		//根据是否永久用户
		if (StringUtil.isNotBlank(screenQueryModel.getPermanent())) {
			queryWrapper.eq(ScreenUser::getPermanent, screenQueryModel.getPermanent());
		}
		//是否非法
		if (screenQueryModel.getForbidden() != null && screenQueryModel.getForbidden() != 0) {
			queryWrapper.eq(ScreenUser::getForbidden, screenQueryModel.getForbidden());
		}
		IPage<ScreenUser> selectUserList = baseMapper.selectPage(page, queryWrapper);
		return R.data(selectUserList);
	}

	/**
	 * 计算用户可用天数
	 * @param screenUser
	 * @return
	 */
	private long popularUseDay(ScreenUser screenUser){
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime permissionEndDate = screenUser.getPermissionEndDate();
		Duration between = Duration.between(now, permissionEndDate);
		return between.toDays();
	}

}
